#pragma once
#include <cstdio>
#include <string>
#include <filesystem>
#include <sstream>
#include <fstream>
#include <memory>
#include <ctime>
#include <unistd.h>
#include <iostream>
#include "Mutex.hpp"
using namespace std;


class LogStrategy
{
public:
    ~LogStrategy() = default;
    virtual void SyncLog(const string &message) = 0;
};
class ConsoleLogStrategy : public LogStrategy
{
public:
    ConsoleLogStrategy() = default;
    ~ConsoleLogStrategy() = default;
    void SyncLog(const string &message) override
    {
        MutexGuard mutexguard(_mutex);
        cout << message << endl;
    }

private:
    Mutex _mutex;
};
const string DefaultPath = "./mylog";
const string DefaultFileName = "my.log";
class FileLogStrategy : public LogStrategy
{
public:
    FileLogStrategy(const string &DefaultPath, const string &DefaultFileName)
        : _path(DefaultPath), _file_name(DefaultFileName)
    {
        MutexGuard mutexguard(_mutex);
        if (filesystem::exists(_path))
        {
            return;
        }
        try
        {
            filesystem::create_directories(_path);
        }
        catch (const filesystem::filesystem_error &e)
        {
            cerr << e.what() << '\n';
        }
    }
    ~FileLogStrategy() = default;

    void SyncLog(const string &message) override
    {
        MutexGuard mutexguard(_mutex);
        string filename = _path + (_path.back() == '/' ? "" : "/") + _file_name;
        ofstream out(filename, ios::app);
        if (!out.is_open())
        {
            return;
        }
        out << message << endl;
        out.close();
    }

private:
    string _path;
    string _file_name;
    Mutex _mutex;
};
enum class LogLevel
{
    DEBUG,
    INFORMATION,
    WARNING,
    ERROR,
    FATAL
};
string GetLogLevel(LogLevel &loglevel)
{
    switch (loglevel)
    {
    case LogLevel::DEBUG:
        return "DEBUGE";
    case LogLevel::INFORMATION:
        return "INFORMATION";
    case LogLevel::WARNING:
        return "WARNING";
    case LogLevel::ERROR:
        return "ERROR";
    case LogLevel::FATAL:
        return "FATAL";
    default:
        return "UNKNOWN";
    }
}
string GetCurrentTime()
{
    time_t t = time(nullptr);
    tm *current_time = localtime(&t);
    int year = current_time->tm_year + 1900;
    int month = current_time->tm_mon + 1;
    int day = current_time->tm_mday;
    int hour = current_time->tm_hour;
    int minute = current_time->tm_min;
    int second = current_time->tm_sec;
    char buffer[80];
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", current_time);
    return buffer;
}
class Log
{
public:
    Log()
    {
        EnableConsoleLogStrategy();
    }
    void EnableFileLogStrategy()
    {
        _fflush_strategy = make_unique<FileLogStrategy>(DefaultPath, DefaultFileName);
    }
    void EnableConsoleLogStrategy()
    {
        _fflush_strategy = make_unique<ConsoleLogStrategy>();
    }
    class LogMessage
    {
    public:
        LogMessage(const LogLevel &level, const string &file_name, int line_number, Log &log)
            : _current_time(GetCurrentTime()), _level(level), _file_name(file_name), _line_number(line_number), _log(log), _pid(getpid())
        {
            stringstream ss;
            ss << "[" << _current_time << "] "
               << "[" << GetLogLevel(_level) << "] "
               << "[" << _pid << "] "
               << "[" << _file_name << "] "
               << "[" << _line_number << "] "
               << "- ";
            _loginfo = ss.str();
        }
        template <typename T>
        LogMessage &operator<<(const T &info)
        {
            stringstream ss;
            ss << info;
            _loginfo += ss.str();
            return *this;
        }
        ~LogMessage()
        {
            if (_log._fflush_strategy)
            {
                _log._fflush_strategy->SyncLog(_loginfo);
            }
        }

    private:
        string _current_time;
        LogLevel _level;
        pid_t _pid;
        string _file_name;
        int _line_number;
        string _loginfo;
        Log &_log;
    };
    LogMessage operator()(LogLevel level, string name, int line)
    {
        return LogMessage(level, name, line, *this);
    }
    ~Log()
    {
    }

private:
    unique_ptr<LogStrategy> _fflush_strategy;
};
Log logger;

// 使用宏，简化用户操作，获取文件名和行号
#define LOG(level) logger(level, __FILE__, __LINE__)
#define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
#define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()